//表格，及基础数据资源
var myDate = new Date();
var startDate = new Date(1, 1, 1);
var endDate = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());
var yesterday = new Date;
yesterday.setDate(myDate.getDate()-1);

$('#my-endDate').text(myDate.getFullYear()+"-"+parseInt(myDate.getMonth()+1)+"-"+myDate.getDate());
$('#my-start').datepicker().
on('changeDate.datepicker.amui', function(event) {
    console.log(endDate.valueOf());
    console.log(event.date.valueOf());
    if (event.date.valueOf() > endDate.valueOf()) {
        layer.alert('开始日期应小于结束日期！');
    } else {
        startDate = new Date(event.date);
        $('#my-startDate').text($('#my-start').data('date'));
    }
    $(this).datepicker('close');
});
$('#my-end').datepicker().
on('changeDate.datepicker.amui', function(event) {
    if (event.date.valueOf() < startDate.valueOf()) {
        layer.alert('结束日期应大于开始日期！');
    } else {
        endDate = new Date(event.date);
        $('#my-endDate').text($('#my-end').data('date'));
    }
    $(this).datepicker('close');
});

$("#monitoringSearch").click(function() {
    $("#facilityMonitoringIsSearch").val(1);
    $("#facilityMonitoringStartDateTemp").val($("#my-startDate").html());
    $("#facilityMonitoringEndDateTemp").val($("#my-endDate").html());
    $("#resourceMonitoringIsSearch").val(1);
    $("#resourceMonitoringStartDateTemp").val($("#my-startDate").html());
    $("#resourceMonitoringEndDateTemp").val($("#my-endDate").html());
    $("#monitoringStatisticsIsSearch").val(1);
    $("#monitoringStatisticsStartDateTemp").val($("#my-startDate").html());
    $("#monitoringStatisticsEndDateTemp").val($("#my-endDate").html());
    $("#jobMonitoringIsSearch").val(1);
    $("#jobMonitoringStartDateTemp").val($("#my-startDate").html());
    $("#jobMonitoringEndDateTemp").val($("#my-endDate").html());
    $("#hardwareMonitoringIsSearch").val(1);
    $("#hardwareMonitoringStartDateTemp").val($("#my-startDate").html());
    $("#hardwareMonitoringEndDateTemp").val($("#my-endDate").html());
});
var paginationMaxLength=8;//分页栏的最大显示条数
var onlyOnePageIsShow = true;//只有一页的时候是否显示
//$(function () {
//    changeChart();
//    paginationInit(2);
//    setInterval(function () {
//        option6.series[0].data[0].value = (Math.random() * 100).toFixed(2) - 0;
//        chart6.setOption(option6, true);
//    },2000);
//});
$.ajax({
    type: "POST",
    url: constUrl+"ClusterInfrastructureMonitor",
    dataType: "json",
    data: {
        onePageCount: "10",
        currentPage: "1"
    },
    success: function (data) {
        addPageNum(data.pageNum, 1);
        addBox(data.message, "facilityMonitoringTableList");
        paginationInit(1);
    }
});
$.ajax({
    type: "POST",
    url: constUrl+"ClusterResourceUsage",
    dataType: "json",
    data: {
        operateType: "showHosts",
        onePageCount: "10",
        currentPage: "1"
    },
    success: function (data) {
        addPageNum(data.result.pageNum, 3);
        addBox(data.result.hosts, "monitoringStatisticsTableList");
        paginationInit(3);
        changeChart();
    }
});
function paginationInit(where){
    $('[am-pagination = pagination_'+where+']').each(function(){
        initPagination($(this), where);
    });
}
function initPagination(element, where){
    element.html('');
    var pagenumber = element.attr('pagenumber');
    var totalpage = element.attr('totalpage');
    var pMaxLength = element.attr('paginationMaxLength');
    var onePageIsShow = element.attr('onlyOnePageIsShow');
    if(isNeedPagination(Number(totalpage),onePageIsShow)){
        var content = '<ul class="am-pagination am-pagination-centered"><li value="0"><a href="javascript:void(0);">«</a></li>';
        for(var i =1; i<=totalpage;i++){
            content +='<li value="'+i+'"><a href="javascript:void(0);">'+i+'</a></li>'
        }
        content +='<li value="-1"><a href="javascript:void(0);">»</a></li></ul>';
        element.append(content);
        element.children('ul').children('li[value='+pagenumber+']').attr('class','am-active');
        setDisplayMaxLength(element,pMaxLength);
        addClickListener(element, where);
    }
}
function isNeedPagination(totalpage,settingfromHTML){
    var condition ;
    if(settingfromHTML == "true"){
        condition = true;
    }else if(settingfromHTML == 'false'){
        condition = false;
    }else {
        condition = onlyOnePageIsShow;
    }
    if(condition && totalpage<1){
        return false;
    }else if(!condition && totalpage<=1){
        return false;
    }
    return true;
}


function setDisplayMaxLength(element,len){
    var currentpage =  Number(element.attr('pagenumber'));
    var totoalpage = Number(element.attr('totalpage'));
    if(checkParamIsPositiveInteger(len)){
        len = Number(len);
    }else{
        len =paginationMaxLength;
    }
    if(len<totoalpage){
        var temp1 = parseInt((len-1)/2);
        var temp2 = parseInt(len/2);
        if(temp1<temp2){
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1 + 1;
        }else{
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1;
        }
        if(leftstart<1){
            rightend +=(1-leftstart);
            leftstart = 1;
        }
        if(rightend>totoalpage){
            if(leftstart>1){
                leftstart -=(rightend-totoalpage);
            }
            rightend =totoalpage;
        }
        if(leftstart<1){
            leftstart=1
        }
        while(leftstart >1){
            element.children('ul').children('li[value = '+(--leftstart)+']').css('display','none');
        }
        while(rightend <totoalpage){
            element.children('ul').children('li[value = '+(++rightend)+']').css('display','none');
        }
    }
}

function checkParamIsPositiveInteger(param){
    var reg = /^[1-9]+[0-9]*]*$/;
    return reg.test(param);
}

//根据页面pagenumber、my_totoalpage更新分页，参数element传的是分页的容器

function addClickListener(element, where){
    element.children('ul').children('li').bind('click',function(){
        var temp = Number($(this).attr('value'));
        var pagenumber = Number($(this).parent().parent().attr('pagenumber'));
        var totalpage = Number($(this).parent().parent().attr('totalpage'));
        if(temp == 0){
            temp = pagenumber-1;
        }else if(temp == -1){
            temp = pagenumber+1;
        }
        if(temp != pagenumber && temp !=0 && temp<=totalpage){
            $(this).parent().parent().attr('pagenumber',temp);
            paginationClick(element.attr("id"), where);
            initPagination(element, where);
        }
        return false;
    })
}
//用户需要自己实现的点击事件，参数为分页容器的id
function paginationClick(pagination_id, where){
    var pagenumber = $('#'+pagination_id+'').attr('pagenumber');
    JSON.stringify(pagenumber);
    if(where == 1){
        if($("#facilityMonitoringIsSearch").val() == 1){
            $.ajax({
                type:"POST",
                url:constUrl+"",
                dataType:"json",
                data: {
                },
                success:function(data){
                    addBox(data.message, 'facilityMonitoringTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        } else {
            $.ajax({
                type:"POST",
                url:constUrl+"ClusterInfrastructureMonitor",
                dataType:"json",
                data: {
                    onePageCount: "10",
                    currentPage: pagenumber
                },
                success:function(data){
                    addBox(data.message, 'facilityMonitoringTableList');
                },
                error:function () {
                }
            });
        }
    }
    if(where == 2){
        if($("#resourceMonitoringIsSearch").val() == 1){
            $.ajax({
                type:"POST",
                url:constUrl+"",
                dataType:"json",
                data: {
                    startDate: $("#runStartDateTemp").val(),
                    endDate: $("#runEndDateTemp").val(),
                    content: $("#runSearchContentTemp").val(),
                    onePageCount: "10",
                    currentPage: pagenumber,
                    operateLog: 0
                },
                success:function(data){
                    addBox(data.result, 'resourceMonitoringTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        } else {
            $.ajax({
                type: "POST",
                url: constUrl+"",
                dataType: "json",
                data: {
                    onePageCount: "10",
                    currentPage: pagenumber
                },
                success: function (data) {
                    addBox(data.result, 'resourceMonitoringTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        }
    }
    if(where == 3){
        if($("#monitoringStatisticsIsSearch").val() == 1){
            $.ajax({
                type:"POST",
                url:constUrl+"ClusterResourceUsage",
                dataType:"json",
                data: {
                    operateType: "searchHostByHostName",
                    hostName: $("#monitoringStatisticsSearchContentTemp").val(),
                    onePageCount : 10,
                    currentPage : pagenumber
                },
                success:function(data){
                    addBox(data.result.hosts, 'monitoringStatisticsTableList');
                    changeChart();
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        } else {
            $.ajax({
                type:"POST",
                url:constUrl+"ClusterResourceUsage",
                dataType:"json",
                data: {
                    operateType: "showHosts",
                    onePageCount: "10",
                    currentPage: pagenumber
                },
                success:function(data){
                    addBox(data.result.hosts, 'monitoringStatisticsTableList');
                    changeChart();
                },
                error:function () {
                }
            });
        }
    }
}

function addBox(data, where){
    $("tr").remove("."+where+"Tr");
    addTr(data, where);
}
function addTr(data, where){
    if(where == "facilityMonitoringTableList"){
        for(var i=0;i<data.length;i++) {
            var trJobTemp = data[i].jobIds;
            var htmlJobTemp = "";
            for (var j=0; j<data[i].jobIds; j++){
                htmlJobTemp += "<a href='javascript:void(0)' onclick='CreateQueryStringWithParam(\"nodeDetail.html?nodeId="+data[i].jobIds[j]+"\")'>"+data[i].jobIds[j]+"</a>,";
            }
            htmlJobTemp = htmlJobTemp.substring(0,htmlJobTemp.length-1);
            $("#"+where).children("tbody").append(
                "<tr class='"+where+"Tr'>" +
                "<td>"+(i+1)+"</td>" +
                "<td>"+data[i].hostName+"</td>" +
                "<td>"+data[i].status+"</td>" +
                "<td>"+data[i].totalNumberOfCPU+"</td>" +
                "<td>"+data[i].jobUsedCPUNumber+"</td>" +
                "<td>"+data[i].ut+"</td>" +//3
                "<td>"+data[i].mem+"</td>" +//10
                "<td>"+data[i].swp+"</td>" +//9
                "<td>"+
                "<div type=\"button\" class=\"am-btn am-btn-default am-radius\" onclick=\"openWorkDetailByHostName('"+data[i].hostName+"')\">查看作业详情</div>" +
                "</td>" +
                "</tr>"
            );
        }
      findTr();
    }
    if(where == "resourceMonitoringTableList"){
        for(var i=0;i<data.length;i++) {
            $("#"+where).children("tbody").append(
                "<tr class='"+where+"Tr'>" +
                "</tr>"
            );
        }
    }
    if(where == "monitoringStatisticsTableList"){
        for(var i=0;i<data.length;i++) {
            $("#"+where).children("tbody").append(
                "<tr class='"+where+"Tr computerTr'>" +
                "<td class='trFtd'><input type='checkbox' name='box' checked value='"+i+"'></td>" +
                "<td>"+data[i].hostName+"</td>" +
                "<td>"+data[i].ut+"</td>" +
                "<td>"+data[i].mem+"</td>" +
                "<td>"+data[i].swp+"</td>" +
                "</tr>"
            );
        }
    }
}
function addPageNum(pageNumber, where){
    $('#prePage'+where).attr("totalpage", pageNumber);
}
function openWorkDetailByHostName(hostName) {
    layer.open({
        type: 2,
        skin: 'layui-layer-lan',
        title: '模型选择',
        fix: false,
        scrollbar:false,
        shadeClose: true,
        maxmin: true,
        area: ['817px', '550px'],
        content: constUrl +'views/monitor/facility/hostDetail.action?hostName='+hostName
    });
}
